package com.zz.hhbl.utils

/**
 * Copyright © 2025 zhun All rights reserved.
 * Created by ZhaoZhun on 2025/2/28 16:06.
 * @author: ZhaoZhun 1820022519@qq.com
 * @version: V1.0
 */
import android.content.Context
import android.speech.tts.TextToSpeech
import android.widget.Toast
import java.util.*

class TextToSpeechUtils private constructor(context: Context) {
    companion object{
        fun newInstance(context: Context):TextToSpeechUtils{
            return TextToSpeechUtils(context)
        }
    }
    private var tts: TextToSpeech? = null
    init {
        tts = TextToSpeech(context) { status ->
            if (status == TextToSpeech.SUCCESS) {
                // 设置语言为中文
                val result = tts?.setLanguage(Locale.CHINA)
                if (result == TextToSpeech.LANG_MISSING_DATA
                    || result == TextToSpeech.LANG_NOT_SUPPORTED
                ) {
                    Toast.makeText(context, "不支持该语言", Toast.LENGTH_SHORT).show()
                }
            } else {
                Toast.makeText(context, "初始化失败", Toast.LENGTH_SHORT).show()
            }
        }
    }

    /**
     * 进行文字转语音
     * @param text 要转换的文字
     */
    fun speak(text: String) {
        tts?.apply {
            // 设置语音速率和音调
            setSpeechRate(1.0f)
            setPitch(1.0f)
            // 进行文字转语音
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
                speak(text, TextToSpeech.QUEUE_FLUSH, null, null)
            } else {
                speak(text, TextToSpeech.QUEUE_FLUSH, null)
            }
        }
    }

    /**
     * 释放资源
     */
    fun release() {
        tts?.stop()
        tts?.shutdown()
    }
}